const { src, dest, watch, series, parallel, env } = require("gulp");
const babel = require("gulp-babel");
const uglify = require("gulp-uglify");
const rename = require("gulp-rename");
const cleanCSS = require("gulp-clean-css");
const sass = require("gulp-sass")(require("sass"));
const concat = require("gulp-concat");
const browserify = require("gulp-browserify");
const gulpHtmlVersion = require("gulp-html-version");
const spritesmith = require("gulp.spritesmith");
const minimist = require("minimist");
const js_obfuscator = require('gulp-js-obfuscator');
const staticPath = "static/";
const viewPath = "../view/index/";
const timestamp = parseInt(new Date().getTime() / 1000);
let options = minimist(process.argv.slice(2));
let envStr = options.env || timestamp;
console.log("gulp env", envStr, typeof envStr);
// js优化
function jsBase() {
	return src(staticPath + "js/**/*.b.js")
		.pipe(
			babel({
				presets: ["@babel/preset-env"],
			})
		)
		.pipe(uglify())
		.pipe(rename({ extname: ".min.js" }))
		.pipe(dest(staticPath + "js/"));
}
// [vue].js文件 es6编译es5 js优化
function jsOrangeVue() {
	let init
	if(envStr === 'watch') {
		init = src([staticPath + "js/orange-vue/**/*.js"]).pipe(
			babel({
				presets: ["@babel/preset-env"],
			})
		)
	}else {
		init = src([staticPath + "js/orange-vue/**/*.js"]).pipe(
			babel({
				presets: ["@babel/preset-env"],
			})
		)
		.pipe(js_obfuscator({
			keepLinefeeds:      true,
			keepIndentations:   true,
			encodeStrings:      true,
			encodeNumbers:      true,
			moveStrings:        true,
			replaceNames:       true,
			variableExclusions: [ '^_get_', '^_set_', '^_mtd_' ]
		  }))
		.pipe(uglify({
			compress: {
                drop_console: true,  // 过滤 console
                drop_debugger: true  // 过滤 debugger
            }
		}))
	}
	return  init.pipe(rename({ extname: ".min.js" }))
		.pipe(dest(staticPath + "js/orange"))
}
// [vue].js文件 es6编译es5 js优化
function jsVue() {
	return src([staticPath + "js/orange-vue/**/*.js"])
		.pipe(
			babel({
				presets: ["@babel/preset-env"],
				plugins: ["@babel/transform-runtime"],
			})
		)
		.pipe(
			browserify({
				insertGlobals: true,
			})
		)
		.pipe(rename({ extname: ".min.js" }))
		.pipe(dest(staticPath + "js/orange"));
}
// js优化并合并
function jsConcat() {
	return src(staticPath + "js/*.cc.js")
		.pipe(
			babel({
				presets: ["@babel/preset-env"],
			})
		)
		.pipe(concat("all.js"))
		.pipe(uglify())
		.pipe(rename({ extname: ".min.js" }))
		.pipe(dest(staticPath + "js/"));
}

function css() {
	return src(staticPath + "css/*.b.scss")
		.pipe(sass({ outputStyle: "compressed" }).on("error", sass.logError))
		.pipe(rename({ extname: ".min.css" }))
		.pipe(dest(staticPath + "css/"))
}

function cssAll() {
	return src(staticPath + "css/*.c.scss")
		.pipe(concat("all.min.scss"))
		.pipe(sass({ outputStyle: "compressed" }).on("error", sass.logError))
		.pipe(dest(staticPath + "css/"));
}

function cssMemberAll() {
	return src(staticPath + "css/*.m.scss")
		.pipe(concat("member.min.scss"))
		.pipe(sass({ outputStyle: "compressed" }).on("error", sass.logError))
		.pipe(dest(staticPath + "css/"));
}

function cssele() {
	return src(staticPath + "css/element-ui-orange.css")
		.pipe(
			cleanCSS({ debug: true }, (details) => {
				console.log(`${details.name}: ${details.stats.originalSize}`);
				console.log(`${details.name}: ${details.stats.minifiedSize}`);
			})
		)
		.pipe(rename({ extname: ".min.css" }))
		.pipe(dest(staticPath + "css/"));
}
//  common 默认编译通用模块， all:编译view所有模板, 
function htmlVersion() {
	let commconHtml = []
	let commonHtmlPath = ''
	let currentPath = envStr && typeof envStr == 'string' ? envStr : 'commmon'
	console.log('asa', envStr && typeof envStr == 'string', currentPath)
	if(currentPath === 'all') {
		commconHtml = [viewPath + "**/*.html"]
		commonHtmlPath = viewPath
	}else {
		commconHtml = [viewPath + currentPath + "/*.html"]
		commonHtmlPath = viewPath + currentPath + '/'
	}
	return src(commconHtml)
		.pipe(
			gulpHtmlVersion({
				paramType: "guid",
			})
		)
		.pipe(dest(commonHtmlPath));
}

function htmlSingleVersion() {
	// common/head.html
	let arr = envStr.split('/')
	arr.splice(arr.length-1,1)
	let commconHtml = viewPath + envStr
	let commonHtmlPathStr = ''
	arr.map(item => commonHtmlPathStr += item + '/')
	let commonHtmlPath = viewPath + commonHtmlPathStr
	return src(commconHtml)
		.pipe(
			gulpHtmlVersion({
				paramType: "guid",
			})
		)
		.pipe(dest(commonHtmlPath));
}

function sprite() {
	console.log("process.env.NODE_ENV", envStr);
	var spriteData = src(staticPath + "image/mp/invite/*.png").pipe(
		spritesmith({
			imgName: `sprite_${envStr}.png`,
			cssName: `sprite_${envStr}.css`,
			padding: 10,
		})
	);
	return spriteData.pipe(dest(staticPath + "image/sprite"));
}

exports.build = parallel(jsBase, jsConcat, cssMemberAll, css, cssAll);
exports.ele = cssele;
exports.html = htmlVersion;
exports.htmlsingle = htmlSingleVersion;
exports.sprite = sprite;
exports.vue = jsOrangeVue;
exports.vueWatch = function(){
	watch(staticPath + "js/orange-vue/**/*.js", jsOrangeVue);
}
exports.quick = parallel(cssAll);
exports.default = function () {
	watch(staticPath + "css/*.b.scss", series(css));
	watch(staticPath + "css/*.c.scss", series(cssAll));
	watch(staticPath + "css/*.m.scss", series(cssMemberAll));
	// watch(staticPath + "js/**/*.b.js", series(jsBase, jsConcat));
	// watch(staticPath + "js/orange-vue/**/*.js", jsOrangeVue);
};
